/**
 * Zhe Jiang HongCheng System Inc.
 * Copyright All Rights Reserved.
 */
package com.zjhcsoft.jbosscache.struts;

import com.opensymphony.xwork2.ActionSupport;
import com.zjhcsoft.jbosscache.util.WebContextHolder;
import org.jboss.cache.Cache;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;

/**
 * FileName : IndexAction.java
 * CreateTime : 11-11-11 上午11:07
 * Description : IndexAction
 *
 * @author : liuys
 * @version : 1.0
 */
public class IndexAction extends ActionSupport {
    private static final Logger logger = LoggerFactory.getLogger(IndexAction.class);
    private String token;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String index() {
        Cache<String, Object> cache = WebContextHolder.getInstance().getJbossCache();
        Node node = cache.getNode("/token");
        if (node != null)
            token = (String) node.get("/token");
        return "jc";
    }

    public String setJbossCache() {
        Cache<String, Object> cache = WebContextHolder.getInstance().getJbossCache();
        Node rootNode = cache.getRoot();

        Node node = cache.getNode("/token");
        Fqn fqn = null;
        if (node == null) {
            fqn = Fqn.fromString("/token");
            node = rootNode.addChild(fqn);
        }
        node.put("/token", randomString());
        return SUCCESS;
    }

    private String randomString() {
        return Integer.toHexString(new Random().nextInt(Integer.MAX_VALUE)).toUpperCase();
    }
}
